%%%-------------------------------------------------------------------
%%% File    : b2bua_main_listener.erl
%%% Author  : Anil Kumar S. R. <sranil@gmail.com>
%%% Description : 
%%%
%%% Created : 26 Aug 2010 by Anil Kumar S. R. <sranil@gmail.com>
%%%-------------------------------------------------------------------
-module(b2bua_main_listener).

-behaviour(gen_server).

%% API
-export([start_link/1]).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
		 terminate/2, code_change/3]).

-include("../include/b2bua.hrl").

-record(state, {}).

%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
%% Function: start_link() -> {ok,Pid} | ignore | {error,Error}
%% Description: Starts the server
%%--------------------------------------------------------------------
start_link([Port]) ->
	process_flag(trap_exit, true),
	gen_server:start_link({local, b2bua_main_listener}, ?MODULE, [Port], []).

%%====================================================================
%% gen_server callbacks
%%====================================================================

%%--------------------------------------------------------------------
%% Function: init(Args) -> {ok, State} |
%%                         {ok, State, Timeout} |
%%                         ignore               |
%%                         {stop, Reason}
%% Description: Initiates the server
%%--------------------------------------------------------------------
init([Port]) ->
    case catch gen_tcp:listen(Port, [binary, {packet, 0}, {ip, {0,0,0,0}}, {active, once}, {reuseaddr, true}]) of
        {ok, Listen_Socket} ->
            ?DEBUG("Listening on Port ~w ~n", [Port]),
            gen_server:cast(self(), {accept_connection, Listen_Socket}),
            {ok, #state{}};
        Error ->
            ?DEBUG("Unable to Listen due to ~w ~n", [Error]),
            {stop, "Unable to open port"}
    end.

%%--------------------------------------------------------------------
%% Function: %% handle_call(Request, From, State) -> {reply, Reply, State} |
%%                                      {reply, Reply, State, Timeout} |
%%                                      {noreply, State} |
%%                                      {noreply, State, Timeout} |
%%                                      {stop, Reason, Reply, State} |
%%                                      {stop, Reason, State}
%% Description: Handling call messages
%%--------------------------------------------------------------------
handle_call(_Request, _From, State) ->
	Reply = ok,
	{reply, Reply, State}.

%%--------------------------------------------------------------------
%% Function: handle_cast(Msg, State) -> {noreply, State} |
%%                                      {noreply, State, Timeout} |
%%                                      {stop, Reason, State}
%% Description: Handling cast messages
%%--------------------------------------------------------------------
handle_cast({accept_connection, Listen_Socket}, State) ->
    case catch gen_tcp:accept(Listen_Socket) of
        {ok, Accept_Socket} ->
			io:format("New Connection Accepted ~n"),
            gen_server:cast(self(), {accept_connection, Listen_Socket}),
            case b2bua_session:start([Accept_Socket]) of
                {ok, PID} ->
                    gen_tcp:controlling_process(Accept_Socket, PID);
                _ ->
                    gen_tcp:close(Accept_Socket)
            end;
        _ ->
			gen_server:cast(self(), {accept_connection, Listen_Socket})
    end,
    {noreply, State};

handle_cast(_Msg, State) ->
	{noreply, State}.

%%--------------------------------------------------------------------
%% Function: handle_info(Info, State) -> {noreply, State} |
%%                                       {noreply, State, Timeout} |
%%                                       {stop, Reason, State}
%% Description: Handling all non call/cast messages
%%--------------------------------------------------------------------
handle_info(_Info, State) ->
	{noreply, State}.

%%--------------------------------------------------------------------
%% Function: terminate(Reason, State) -> void()
%% Description: This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any necessary
%% cleaning up. When it returns, the gen_server terminates with Reason.
%% The return value is ignored.
%%--------------------------------------------------------------------
terminate(_Reason, _State) ->
	ok.

%%--------------------------------------------------------------------
%% Func: code_change(OldVsn, State, Extra) -> {ok, NewState}
%% Description: Convert process state when code is changed
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
	{ok, State}.

%%--------------------------------------------------------------------
%%% Internal functions
%%--------------------------------------------------------------------
